package com.jdk.demo.nio.bytebuffer;

import java.nio.ByteBuffer;

public class DuplicateAndSlice {
	
	// duplicate：创建共享此缓冲区内容的新的字节缓冲区。新缓冲区的内容将为此缓冲区的内容
	// slice：创建新的字节缓冲区，内容是此缓冲区内容的共享子序列。新缓冲区的内容将从此缓冲区的当前位置开始
	public static void main(String[] args) {
		byte[] byteArrayIn1 = {1, 2, 3, 4, 5};
		ByteBuffer bytebuffer1 = ByteBuffer.wrap(byteArrayIn1);
		bytebuffer1.position(2);
		System.out.println("bytebuffer1 capacity=" + bytebuffer1.capacity() + ", position=" + bytebuffer1.position() + " limit=" + bytebuffer1.limit());
		
		ByteBuffer bytebuffer2 = bytebuffer1.slice();
		ByteBuffer bytebuffer3 = bytebuffer1.duplicate();
		System.out.println("bytebuffer2 capacity=" + bytebuffer2.capacity() + ", position=" + bytebuffer2.position() + " limit=" + bytebuffer2.limit());
		System.out.println("bytebuffer2 arrayOffset=" + bytebuffer2.arrayOffset());
		System.out.println("bytebuffer3 capacity=" + bytebuffer3.capacity() + ", position=" + bytebuffer3.position() + " limit=" + bytebuffer3.limit());
		System.out.println("bytebuffer3 arrayOffset=" + bytebuffer3.arrayOffset());
	
		bytebuffer2.position(0);
		for (int i = bytebuffer2.position(); i < bytebuffer2.limit(); i++) {
			System.out.print(bytebuffer2.get(i) + " ");
		}
		System.out.println();
		
		bytebuffer3.position(0);
		for (int i = bytebuffer3.position(); i < bytebuffer3.limit(); i++) {
			System.out.print(bytebuffer3.get(i) + " ");
		}
		System.out.println();
	}

}
